import {map_set_bigemap} from '@/consts';

// import { noop } from './helper';
const noop = () => {};

// const host = import.meta.env.VITE_APP_BM_Config_HTTP_URL;

export interface Options {
  exportGetter?: () => any | undefined;
}

function getScriptAsync({ exportGetter = noop }: Options): Promise<any> {
  return new Promise<{ [x: string]: any }>(async (resolve, reject) => {
    if (window.BM) { return resolve(exportGetter()) }

    const host = await map_set_bigemap.value.__getValue('server_root'); 

    const link = document.createElement('link');
    link.rel = 'stylesheet';
    // link.href = `${host}/bigemap.js/v2.1.0/bigemap.css`;
    link.href = host + await map_set_bigemap.value.__getValue('css_path');
    document.head.appendChild(link);
    //
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.defer = true;
    // script.src = `${host}/bigemap.js/v2.1.0/bigemap.js`;
    script.src = host + await map_set_bigemap.value.__getValue('js_path');
    const sc1 = document.createElement('script');
    sc1.type = 'text/javascript';
    sc1.src = '/vendor/bigemap/bm.draw.min.js';

    const ret =  new Promise((resl, rej) => {
      script.onload = () => {
        resl(0)
      };
      script.onerror = () => rej(new Error('script load error'));
    }).then(() => {
      const next =  new Promise((resl, rej) => {
        sc1.onload = () => {
          resl(0)
        };
        sc1.onerror = () => rej(new Error('script load error'));
      });

      document.body.appendChild(sc1);
      return next;
    }).then(() => {
      resolve(exportGetter());

      const lk1 = document.createElement('link');
      lk1.rel = 'stylesheet';
      lk1.href = '/vendor/bigemap/Bigemap.draw.css';
      document.head.appendChild(lk1);
    }).catch(() => {
      reject(new Error('script load error'));
    });
    
    // script.onerror = () => reject(new Error('script load error'));
    document.body.appendChild(script);

    return ret;
  });
}
export default getScriptAsync;
